package top.mingyi4cjh.cms.common.utils;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;
import top.mingyi4cjh.cms.common.error.BusinessException;
import top.mingyi4cjh.cms.common.error.EmBusinessError;
import top.mingyi4cjh.cms.service.RedisService;
import top.mingyi4cjh.cms.viewobject.UserVO;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static top.mingyi4cjh.cms.common.utils.Field.LOGIN_USER;
import static top.mingyi4cjh.cms.common.utils.Field.ONE_DAY;
import static top.mingyi4cjh.cms.common.utils.RedisPrefix.USER_INFO;


/**
 * @author MingYi
 */
@Component
public class UserInfoUtils {
    @Resource
    private RedisService redisService;

    public String getLoginUserId(HttpServletRequest request) {
        String token = request.getHeader("token");
        DecodedJWT decodedJwt = JwtUtils.verify(token);
        String userId = decodedJwt.getClaim(LOGIN_USER).asString();
        return userId;
    }

    public UserVO getLoginUserInfo(Long userId) {
        String key = USER_INFO.getPrefix() + userId;
        String value = (String) redisService.get(key);
        if (value == null) {
            throw new BusinessException(EmBusinessError.TOKEN_EXPIRED);
        }
        UserVO userVO = JSON.parseObject(value, UserVO.class);
        return userVO;
    }

    public void setUserInfo(Long userId, UserVO userInfo) {
        String key = USER_INFO.getPrefix() + userId;
        String value = JSON.toJSONString(userInfo);
        redisService.set(key, value, ONE_DAY);
    }

    /**
     * 从request的Header中获取token。
     *
     * @param request HttpServletRequest
     * @return token
     */
    public String getToken(HttpServletRequest request) {
        return request.getHeader("token");
    }
}
